//
//  RadioPlayViewController.m
//  Leisure
//
//  Created by 大展 on 16/7/4.
//  Copyright © 2016年 大展. All rights reserved.
//

#import "RadioPlayViewController.h"

@interface RadioPlayViewController ()<UITableViewDelegate, UITableViewDataSource,PlayManagerDelegate>
@property (weak, nonatomic) IBOutlet UIWebView *webView;
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (weak, nonatomic) IBOutlet UIImageView *coverimg;
@property (weak, nonatomic) IBOutlet UISlider *slider;
@property (nonatomic, assign)NSInteger currentIndex;
@property (nonatomic, strong)UIView *greenView;
@end

@implementation RadioPlayViewController


- (UIView *)greenView {

    if (!_greenView) {



        _greenView = [[UIView alloc]initWithFrame:CGRectMake(kWidth -10, 0, 10, [self fetchCellWithIndex:0].frame.size.height)];
        _greenView.backgroundColor = [UIColor greenColor];
    }
    return _greenView;
}

// 单例
+ (instancetype)sharedManager {

    static RadioPlayViewController *handle = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{

        handle = [[RadioPlayViewController alloc]initWithNibName:@"RadioPlayViewController" bundle:nil];
    });
    return handle;
}

- (void)viewDidLoad {
    [super viewDidLoad];

    self.webView.backgroundColor = [UIColor clearColor];
    
    self.webView.opaque = NO;
    self.currentIndex = -1;
    self.navigationController.navigationBar.translucent = NO;
    self.automaticallyAdjustsScrollViewInsets = NO;
    [self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"cell"];
    [PlayManager sharedManager].delegate = self;

    self.navigationItem.rightBarButtonItem = ({

        UIBarButtonItem *item = [[UIBarButtonItem alloc]initWithTitle:@"下载" style:(UIBarButtonItemStylePlain) target:self action:@selector(downloadAction)];

        item;
    });
}

- (void)downloadAction {

    DownloadManager *manager = [DownloadManager sharedManager];

    // 先判断有没有正在下载
    Download *download = [manager findDownloadWithModel:self.dataSource[self.currentIndex]];

    if (download) {

        NSLog(@"已经正在下载");
    } else {

        // 没有下载的时候在进行下载
        download = [manager addDownloadWithModel:self.dataSource[self.currentIndex]];

    }



    
}
- (IBAction)playLastOne:(id)sender {

    if (self.currentIndex == 0) {

        self.currentIndex = self.dataSource.count;
    }
    self.currentIndex--;
    [self setRadioInfoWithIndex:self.currentIndex];


}
- (IBAction)playOrPause:(id)sender {

    if ([[PlayManager sharedManager]isPlaying]) {

        [[PlayManager sharedManager]pauseMusic];
    }else{

        [[PlayManager sharedManager]playMusic];
    }
    
}

- (IBAction)playNextOne:(id)sender {

    if (self.currentIndex == self.dataSource.count-1) {

        self.currentIndex = 0;
    }
    self.currentIndex++;
    [self setRadioInfoWithIndex:self.currentIndex];
}

- (IBAction)sliderAction:(UISlider *)sender {

    [[PlayManager sharedManager]playMusicWithSliderValue:sender.value];

}

- (void)viewDidAppear:(BOOL)animated {

    [self.tableView reloadData];
    // 为了防止点同一首歌重新播放的情况发生
    if (self.index != self.currentIndex) {

        self.currentIndex = self.index;
        // 设置信息
        [self setRadioInfoWithIndex:self.currentIndex];
    }
}



- (void)setRadioInfoWithIndex:(NSInteger)index {

    RadioDetailModel *radio = self.dataSource[index];

    // 子线程用来播放，处理耗时的操作
    dispatch_async(dispatch_get_global_queue(0, 0), ^{

        // 播放
        [[PlayManager sharedManager] prepareToPlayMusicWithUrl:radio.musicUrl];
        [self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:radio.webview_url]]];

        // 主线程，主要用来刷新UI的（使用完子线程后，要回到主线程）
        dispatch_async(dispatch_get_main_queue(), ^{


            self.title = radio.title;
            [self.greenView removeFromSuperview];
            [[self fetchCellWithIndex:self.currentIndex].contentView addSubview:self.greenView];
            [self.coverimg sd_setImageWithURL:[NSURL URLWithString:radio.imgUrl]];
        });
    });
}

- (UITableViewCell *)fetchCellWithIndex:(NSInteger)index {

    UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:index inSection:0]];
    return cell;
}

- (void)playManagerDelegateFetchTotalTime:(NSString *)totalTime currentTime:(NSString *)currentTime progress:(CGFloat)progress {

    self.slider.value = progress;
}

- (void)playToNextMusic {

    [self playNextOne:nil];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

    return self.dataSource.count;;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    UITableViewCell *cell= [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];

    cell.textLabel.text = [self.dataSource[indexPath.row] title];
    return cell;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
